<script setup lang="ts">
import { getPatientList } from '@/services/user'
import type { Patient } from '@/types/user'
import { showConfirmDialog, type FormInstance, showSuccessToast, showToast } from 'vant'
import { onMounted, computed } from 'vue'
import { ref } from 'vue'
import { nameRules, cardIdRules } from '@/utils/rules'
import { addPatient, getPatientDetails, updatePatientInfo, delPatientInfo } from '@/services/user'
import { useRoute } from 'vue-router'
import { useConsultStore } from '@/stores'
import { useRouter } from 'vue-router'
const route = useRoute()
const store = useConsultStore()
const router = useRouter()
// 患者档案列表数据
const patientList = ref<Patient[]>([])
//姓名枚举数据
const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]
// 初始化渲染
const loadList = async () => {
  const res = await getPatientList()
  patientList.value = res.data
  if (isChange.value && patientList.value.length) {
    const defPatient = patientList.value.find((item) => item.defaultFlag === 1)
    if (defPatient) patientId.value = defPatient.id
    else patientId.value = patientList.value[0].id
  }
}
onMounted(() => {
  //初始化渲染档案列表
  loadList()
})

// 打开侧边栏
const show = ref(false)
const showPopup = () => {
  //重置表单数据
  patient.value = { ...initPatient }
  show.value = true
}

/* --------侧边栏表单功能-------- */

//患者表单初始数据
const initPatient: Patient = {
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 0
}

//患者表单数据
const patient = ref<Patient>({ ...initPatient })

//计算默认数据转换
const defaultFlag = computed({
  get: () => patient.value.defaultFlag === 1,
  set: (value) => {
    patient.value.defaultFlag = value ? 1 : 0
  }
})

//表单提交数据
const form = ref<FormInstance>()

//档案表单提交
const submit = async () => {
  await form.value?.validate()
  await verifyNameForCardId()
  // 校验通过
  patient.value.id ? await updatePatientInfo(patient.value) : await addPatient(patient.value)
  show.value = false
  loadList()
  showSuccessToast(patient.value.id ? '修改成功' : '添加成功')
}

//性别联合姓名校验
const verifyNameForCardId = async () => {
  // 身份证倒数第二位，单数是男，双数是女
  const gender = +patient.value.idCard.slice(-2, -1) % 2
  if (gender !== patient.value.gender) {
    return await showConfirmDialog({
      title: '温馨提示',
      message: '填写的性别和身份证号中的不一致\n您确认提交吗？'
    })
  }
}

// 档案数据回显------
const filesEcho = async (ev: MouseEvent, id: string) => {
  const res = await getPatientDetails(id)
  patient.value = res.data
  show.value = true
}

//删除档案数据------
const delPatient = async () => {
  await showConfirmDialog({
    title: '温馨提示',
    message: `确认删除 ${patient.value.name} 的患者档案？`
  })
  await delPatientInfo(patient.value.id as string)
  showSuccessToast('删除成功!')
  patientList.value = patientList.value.filter((v) => v.id !== patient.value.id)
  show.value = false
}

// 患者选择------
const isChange = computed(() => route.query.isChange === '1')
const patientId = ref<string>()
const selectedPatient = (item: Patient) => {
  if (isChange.value) {
    patientId.value = item.id
  }
}

// 跳转支付页
const next = async () => {
  if (!patientId.value) return showToast('请选就诊择患者')
  store.setPatient(patientId.value)
  router.push('/consult/pay')
}
</script>

<template>
  <div class="patient-page">
    <!-- 导航栏 -->
    <cp-nav-bar :title="isChange ? '选择患者' : '家庭档案'"></cp-nav-bar>
    <!-- 头部提示 -->
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <!-- 列表 -->
    <div class="patient-list">
      <div
        class="patient-item"
        :class="{ selected: patientId === patient.id }"
        @click="selectedPatient(patient)"
        v-for="patient in patientList"
        :key="patient.id"
      >
        <div class="info">
          <span class="name">{{ patient.name }}</span>
          <span class="id">{{ patient.idCard.replace(/^(.{6}).+(.{4})$/, '\$1****\$2') }}</span>
          <span>{{ patient.genderValue }}</span>
          <span>{{ patient.age }}岁</span>
        </div>
        <div class="icon" @click="filesEcho($event, patient.id || '')">
          <cp-icon name="user-edit" />
        </div>

        <div class="tag" v-if="patient.defaultFlag === 1">默认</div>
      </div>
      <div class="patient-add" v-if="patientList.length < 6" @click="showPopup()">
        <cp-icon name="user-add" />
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可添加 6 人</div>
    </div>
    <!-- 底部按钮 -->
    <div class="patient-next" v-if="isChange">
      <van-button type="primary" round block @click="next">下一步</van-button>
    </div>
    <!-- 侧边栏 -->
    <van-popup v-model:show="show" position="right">
      <cp-nav-bar
        :back="() => (show = false)"
        :title="patient.id ? '编辑患者档案' : '新增患者档案'"
        right-text="保存"
        @click-right="submit()"
      ></cp-nav-bar>
      <van-form autocomplete="off" ref="form">
        <van-field
          :rules="nameRules"
          v-model="patient.name"
          label="真实姓名"
          placeholder="请输入真实姓名"
        />
        <van-field
          :rules="cardIdRules"
          v-model="patient.idCard"
          label="身份证号"
          placeholder="请输入身份证号"
        />
        <van-field label="性别" class="pb4">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn :options="options" v-model="patient.gender"></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox v-model="defaultFlag" :icon-size="18" round />
          </template>
        </van-field>
      </van-form>
      <van-action-bar v-if="patient.id">
        <van-action-bar-button @click="delPatient()">删除</van-action-bar-button>
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 46px 0 80px;

  :deep() {
    .van-popup {
      width: 100%;
      height: 100%;
      padding-top: 46px;
      box-sizing: border-box;
    }
  }
}

.patient-list {
  padding: 15px;
}

.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;

  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;

    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;

      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }

      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }

  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }

  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);

    .icon {
      color: var(--cp-primary);
    }
  }
}

.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;

  .cp-icon {
    font-size: 24px;
  }
}

.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}

.patient-del-tip {
  color: red;
  font-size: 14px;
}

.pb4 {
  padding-bottom: 4px;
}

.van-action-bar {
  padding: 0 10px;
  margin-bottom: 10px;

  .van-button {
    color: var(--cp-price);
    background-color: var(--cp-bg);
  }
}
</style>
